package com.dxy.yzs.marathon.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dxy.yzs.marathon.common.Constants;
import com.dxy.yzs.marathon.common.exception.InvalidUserInfoException;
import com.dxy.yzs.marathon.common.exception.UserNotExistException;
import com.dxy.yzs.marathon.domain.MessageContact;
import com.dxy.yzs.marathon.domain.MessageContent;
import com.dxy.yzs.marathon.domain.User;
import com.dxy.yzs.marathon.mapper.ImMsgContactMapper;
import com.dxy.yzs.marathon.mapper.ImMsgContentMapper;
import com.dxy.yzs.marathon.service.UserService;
import com.dxy.yzs.marathon.mapper.UserMapper;
import com.dxy.yzs.marathon.vo.MessageContactVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 *
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ImMsgContactMapper contactMapper;
    @Autowired
    private ImMsgContentMapper contentMapper;
    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public User login(String username, String password) {
        List<User> users = userMapper.selectList(new QueryWrapper<User>().eq("username",username));
        if (null == users || users.isEmpty()) {
            log.warn("该用户不存在:" + username);
            throw new UserNotExistException("该用户不存在:" + username);
        } else {
            User user = users.get(0);
            if (user.getPassword().equals(password)) {
                log.info(user.getUsername() + " logged in!");
                return user;
            } else {
                log.warn(user.getUsername() + " failed to log in!");
                throw new InvalidUserInfoException("invalid user info:" + user.getUsername());
            }
        }
    }

    @Override
    public List<User> getAllUsersExcept(User exceptUser) {
        List<User> otherUsers = userMapper.selectList(new QueryWrapper<User>()
        .ne("id",exceptUser.getId()));
        return otherUsers;
    }

    @Override
    public MessageContactVO getContacts(User ownerUser) {
        List<MessageContact> contacts =  contactMapper.selectList(
                new QueryWrapper<MessageContact>()
                .eq("owner_uid",ownerUser.getId())
                .orderByDesc("mid")
        );
        if (contacts != null) {
            long totalUnread = 0;
            Object totalUnreadObj = redisTemplate.opsForValue().get(ownerUser.getId() + "_T");
            if (null != totalUnreadObj) {
                totalUnread = Long.parseLong(totalUnreadObj+"");
            }

            final MessageContactVO contactVO = new MessageContactVO(ownerUser.getId(), ownerUser.getUsername(), ownerUser.getAvatar(), totalUnread);
            contacts.stream().forEach(contact -> {
                Integer mid = contact.getMid();
                MessageContent contentVO = contentMapper.selectById(mid);
                User otherUser = userMapper.selectById(contact.getOtherUid());

                if (null != contentVO) {
                    long convUnread = 0;
                    Object convUnreadObj = redisTemplate.opsForHash().get(ownerUser.getId() + "_C", otherUser.getId()+"");
                    if (null != convUnreadObj) {
                        convUnread = Long.parseLong(convUnreadObj+"");
                    }
                    MessageContactVO.ContactInfo contactInfo = contactVO.new ContactInfo(otherUser.getId(), otherUser.getUsername(), otherUser.getAvatar(), mid, contact.getType(), contentVO.getContent(), convUnread, contact.getCreateTime());
                    contactVO.appendContact(contactInfo);
                }
            });
            return contactVO;
        }
        return null;
    }
}




